#include "rule.h"

KIND_OF_CARDS get_kind_of_cards(POKER_CARD *poker_cards, int len)
{
    int compare_suit(const void *, const void *);
    int compare_color(const void *, const void *);
    KIND_OF_CARDS kind = OFF_SUIT;
    KIND_OF_CARDS last_kind = OFF_SUIT;
    int len_card = sizeof(*poker_cards);
    qsort(poker_cards, len, len_card, compare_suit);
    if (poker_cards[len - 1].suit == ACE)
        kind = ACE_HIGH;

    if (poker_cards[0].suit == poker_cards[len - 1].suit && len >= 3 && len <= 4)
        kind = SET;
    else
    {
        if (poker_cards[0].suit + len - 1 == poker_cards[len - 1].suit)
            kind = STRAIGHT;

        if (kind != STRAIGHT && kind == ACE_HIGH && poker_cards[0].suit + len - 2 == poker_cards[len - 2].suit)
            kind = STRAIGHT;

        for (size_t i = 0; i < len; i++)
        {
            if (i != len - 1 && poker_cards[i].suit == poker_cards[i + 1].suit)
            {
                kind = PAIR;
                break;
            }
        }

        if (kind != PAIR)
        {
            last_kind = kind;
            qsort(poker_cards, len, len_card, compare_color);
            if (poker_cards[0].color == poker_cards[len - 1].color)
                kind = SUITED;
        }

        if (last_kind == STRAIGHT && kind == SUITED)
        {
            kind = SUITED_AND_STRAIGHT;
        }
    }

    return kind;
}

char *get_kind_str(KIND_OF_CARDS kind)
{
    char *str;
    switch (kind)
    {
    case SET:
        str = "三条";
        break;
    case SUITED_AND_STRAIGHT:
        str = "同花顺";
        break;
    case STRAIGHT:
        str = "顺子";
        break;
    case SUITED:
        str = "同花";
        break;
    case PAIR:
        str = "对子";
        break;
    case ACE_HIGH:
        str = "A字头";
        break;
    default:
        str = "普通牌";
        break;
    }

    return str;
}

int compare_suit(const void *x, const void *y)
{
    return ((POKER_CARD *)x)->suit - ((POKER_CARD *)y)->suit;
}

int compare_color(const void *x, const void *y)
{
    return ((POKER_CARD *)x)->color - ((POKER_CARD *)y)->color;
}